import os
import uuid
import tempfile
import requests
from PIL import Image
from fastapi import HTTPException
from models.models import ConvertRequest, ConvertResponse


async def convert_webp_to_png(request: ConvertRequest) -> ConvertResponse:
    """
    Convert WebP image to PNG format.
    
    Args:
        request: ConvertRequest containing the WebP image URL
        
    Returns:
        ConvertResponse with success status and PNG image URL
    """
    try:
        # 下载WebP图片到临时文件
        response = requests.get(request.image_url, timeout=30)
        response.raise_for_status()
        
        # 创建临时文件
        with tempfile.NamedTemporaryFile(suffix='.webp', delete=False) as temp_file:
            temp_file.write(response.content)
            temp_webp_path = temp_file.name
        
        try:
            # 使用Pillow打开WebP图片
            with Image.open(temp_webp_path) as img:
                # 生成唯一的PNG文件名
                png_filename = f"{uuid.uuid4()}.png"
                png_path = os.path.join("static", png_filename)
                
                # 确保static目录存在
                os.makedirs("static", exist_ok=True)
                
                # 转换为PNG并保存
                img.save(png_path, "PNG")
                
                # 返回可访问的PNG完整URL
                png_url = f"http://localhost:8000/static/{png_filename}"
                
                return ConvertResponse(
                    success=True,
                    convert_image_url=png_url
                )
                
        finally:
            # 清理临时文件
            if os.path.exists(temp_webp_path):
                os.unlink(temp_webp_path)
                
    except requests.RequestException as e:
        raise HTTPException(status_code=400, detail=f"Failed to download image: {str(e)}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Conversion failed: {str(e)}")
